/*
    Copyright  Louis CHEREL cherel.louis@gmail.com  
    This file is part of Agenda de l'Efrei.

    Agenda de l'Efrei is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Agenda de l'Efrei is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Agenda de l'Efrei.  If not, see <http://www.gnu.org/licenses/>.
 */
package fr.efrei.AgendaEfrei;


import android.app.Fragment;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.util.Xml;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileReader;
import org.xmlpull.v1.XmlPullParser;

public class ViewSemesterFragment extends Fragment {

    protected MenuItem mProgressbar;
    protected int mSemester;
    protected boolean mLoaded=false;
    protected TableLayout tl;
    
    public ViewSemesterFragment(int semester){
        super();
        mSemester = semester;
    }

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.page, container, false);
        tl = (TableLayout) rootView.findViewById(R.id.view_notes);
        new NotesUpdater(this.getActivity()).execute();
        showNotes();
        return rootView;
    }

    public void showNotes() {
        new AsyncTask<Context, Void, Void>() {
            private Context mContext;

            @Override
            public Void doInBackground(Context... c) {
                mContext = c[0];
                while (ViewNotes.getIsNotesUpdaterLaunched()) {
                }
                ViewNotes.setIsshowNotesLaunched(true);
                publishProgress();
                return null;
            }

            @Override
            public void onProgressUpdate(Void... v) {
                Toast toast = null;
                if (ViewNotes.getIsUpdateNeeded() || !mLoaded) {
                    Log.v("ViewSemesterFragment","showNotes "+mSemester);
                    tl.removeAllViews();
                    boolean isUE = false;
                    TextView tv = null;
                    TableRow tr = null;
                    FileReader file = null;
                    try {
                        File test = new File(mContext.getFilesDir(), "notes_p1"+mSemester);
                        if (test.exists()) {
                            try {
                                XmlPullParser parser = Xml.newPullParser();
                                parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);

                                file = new FileReader(mContext.getFilesDir() + "/notes_p1"+mSemester);
                                parser.setInput(file);
                                parser.nextTag();
                                parser.require(XmlPullParser.START_TAG, null, "table");
                                tl.setBackgroundColor(Color.parseColor("#50AB9D"));


                                while (parser.next() != XmlPullParser.END_DOCUMENT) {

                                    if (parser.getEventType() != XmlPullParser.START_TAG) {
                                        continue;
                                    }

                                    String name = parser.getName();


                                    if (name.equals("tr")) {

                                        if (parser.getAttributeValue(null, "class") == null) {
                                            tr = new TableRow(mContext);
                                            tl.addView(tr);
                                            tr.setBackgroundColor(Color.parseColor("#FFFFFF"));
                                            TableLayout.LayoutParams lp = (TableLayout.LayoutParams) tr.getLayoutParams();
                                            lp.setMargins(0, 1, 0, 1);
                                        } else {
                                            if (parser.getAttributeValue(null, "class").equals("UE")) {
                                                isUE = true;
                                                tr = new TableRow(mContext);
                                                tl.addView(tr);
                                                tr.setBackgroundColor(Color.parseColor("#1F8172"));
                                            }
                                        }
                                    } else if (name.equals("th") || name.equals("td")) {

                                        if (parser.next() == XmlPullParser.TEXT) {
                                            tv = new TextView(mContext);


                                            if (tr != null) {
                                                tr.addView(tv);
                                                
                                                tv.setPadding(10, 5, 10, 5);
                                                String contenuTxt = parser.getText();
                                                contenuTxt = contenuTxt.replace(" / ", "\n");
                                                tv.setText(contenuTxt);


                                                if (isUE) {
                                                    tv.setTypeface(tv.getTypeface(), Typeface.BOLD);
                                                    tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, 20);
                                                    tv.setTextColor(Color.parseColor("#CECFCF"));
                                                    isUE = false;
                                                } else if (name.equals("th")) {
                                                    tv.setTypeface(tv.getTypeface(), Typeface.BOLD);
                                                    tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, 23);
                                                } else {
                                                    tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, 18);
                                                }
                                            }
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                Log.w("AsyncTask VN", "[1]" + e.toString());
                            }
                        } else {
                            tr = new TableRow(mContext);
                            tl.addView(tr);
                            tv = new TextView(mContext);
                            tr.addView(tv);
                            tv.setText("Impossible de récupérer vos notes:\n\t- Vous n'avez pas entré vos identifiants\n\t- Vous avez entré des identifiants erronés\n\t- Vous n'avez pas accès à internet");
                        }
                    } catch (Exception e) {
                        Log.w("AsyncTask VN", "[2]" + e.toString());
                    }
                }
                if(mLoaded){
                    if (ViewNotes.getIsUpdateNeeded() && ViewNotes.getIsUpdateError() == 0) {
                        toast = Toast.makeText(mContext, "Mise à jour effectuée", Toast.LENGTH_SHORT);
                    } else if (ViewNotes.getIsUpdateError() != 0) {
                        toast = Toast.makeText(mContext, "Impossible de récupérer vos notes:(Erreur #" + ViewNotes.getIsUpdateError() + ")\n\t- Vous n'avez pas entré vos identifiants\n\t- Vous avez entré des identifiants erronés\n\t- Vous n'avez pas accès à internet", Toast.LENGTH_SHORT);
                        ViewNotes.setIsUpdateError(0);
                    } else {
                        toast = Toast.makeText(mContext, "Aucune mise à jour.", Toast.LENGTH_SHORT);
                    }
                    toast.show();
                }
                else
                    mLoaded=true;

                ViewNotes.setIsUpdateNeeded(false);
                ViewNotes.setIsshowNotesLaunched(false);
                if (mProgressbar != null) {
                    mProgressbar.collapseActionView();
                    mProgressbar.setActionView(null);
                }
            }
        }.execute(this.getActivity());
    }
}
